package com.yupi.springbootinit.service.impl;

import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yupi.springbootinit.model.entity.Picture;
import com.yupi.springbootinit.service.PictureService;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
public class PictureServiceImpl implements PictureService {
    @Override
    public Page<Picture> searchPictureByKey(String searchText, long pageNum, long pageSize) {
        long count = (pageNum - 1) * pageSize; // 模拟分页效果
        String url = String.format("https://www.bing.com/images/search?q=%s&first=%s",searchText,count);
        List<Picture> pictureList = new ArrayList<>();
        try {
            Document document = Jsoup.connect(url).get();
            // 通过定位到对应的 css 样式 来获取想要的元素列表
            Elements elements = document.select(".iuscp.isv");
            for (Element element : elements) {
                if (pictureList.size() >= pageSize) {
                    break;
                }
                // 获取图片路径
                String m = element.select(".iusc").get(0).attr("m");
                Map<String, Object> map = JSONUtil.toBean(m, Map.class);
                String murl = (String) map.get("murl");
                // 获取标题内容
                String title = element.select(".inflnk").get(0).attr("aria-label");
                Picture picture = new Picture();
                picture.setTitle(title);
                picture.setSrc(murl);
                pictureList.add(picture);
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        Page<Picture> picturePage = new Page<>(pageNum, pageSize);
        picturePage.setRecords(pictureList);
        return picturePage;
    }
}
